<?php

namespace app\controllers;

use app\components\AlertWidget;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;

class BaseController extends Controller
{

    public $enableCsrfValidation = false;

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        $behaviors['access'] = [
            'class' => AccessControl::class,
            'rules' => [
                //login只能在未登录的时候访问
                [
                    'controllers' => ['site'],
                    'actions' => ['login'],
                    'allow' => true,
                    'roles' => ['?'],
                ],
                //logout,index,main只要登录后就可以访问
                [
                    'controllers' => ['site'],
                    'actions' => ['login', 'logout', 'index', 'main', 'update-password'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
            'denyCallback' => function ($rule, $action) {
                if (Yii::$app->user->isGuest) {
                    return Yii::$app->user->loginRequired();
                }
                if (Yii::$app->request->isAjax) {
                    return $this->error('您无权限执行此操作');
                } else {
                    exit($this->alert('您无权限访问此页面', 403));
                }
            },
        ];

        $module = Yii::$app->controller->module->id;
        $controller = $module != 'basic' ? $module . '/' . Yii::$app->controller->id : Yii::$app->controller->id;
        $action = Yii::$app->controller->action->id;
        $perm = Yii::$app->session->get('perm');
        //追加权限，如果登录了，是超管||是common模块||有权限赋予访问权限
        if (!Yii::$app->user->isGuest && (Yii::$app->user->identity->is_super || $module == 'common' || in_array("$controller/$action", $perm))) {
            $behaviors['access']['rules'][] = [
                'controllers' => [$controller],
                'actions' => [$action],
                'allow' => true,
                'roles' => ['@'],
            ];
        }

        return $behaviors;
    }

    public function success($data = [], $msg = '')
    {
        $result = ['code' => 0, 'error' => 0, 'data' => $data, 'msg' => $msg];
        return $this->asJson($result);
    }

    public function error($msg = '')
    {
        if (is_array($msg)) {
            foreach ($msg as $key => $val) {
                $msg = $val[0];
                break;
            }
        }
        $result = ['code' => 1, 'error' => 1, 'msg' => $msg];
        return $this->asJson($result);
    }

    public function alert($msg = '您查看的页面不存在', $code = 404)
    {
        return $this->render('//site/alert', ['msg' => $msg, 'code' => $code]);
    }
}
